package com.gugu.procedure.interceptor;


import com.gugu.procedure.common.Constant;
import com.gugu.procedure.common.HttpServletResponseUtils;
import com.gugu.procedure.common.JwtOperator;
import com.gugu.procedure.common.MessageResult;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class CourierInterceptor implements HandlerInterceptor {


    @Resource
    private JwtOperator jwtOperator;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            String token = request.getHeader(Constant.TOKEN);
            if (!StringUtils.hasText(token)) {
                HttpServletResponseUtils.returnErrorResponse(response, MessageResult.error(-1, "Token为空,请重新登录！"));
                return false;
            }
            Claims claims = jwtOperator.getClaimsFromToken(token);
            request.setAttribute(Constant.ACCOUNT, claims.get(Constant.ACCOUNT));
            request.setAttribute(Constant.ROLE, claims.get(Constant.ROLE));
            request.setAttribute(Constant.MOBILE, claims.get(Constant.MOBILE));
            request.setAttribute(Constant.NAME, claims.get(Constant.NAME));
            request.setAttribute(Constant.TIME, claims.get(Constant.TIME));
            return true;
        } catch (Exception e) {
            HttpServletResponseUtils.returnErrorResponse(response, MessageResult.error(-1, "Token失效,请重新登录！"));
            return false;
        }
    }

}
